﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using LIM.controller;
using Telerik.WinControls.UI;
using Telerik.WinControls.Data;

namespace LIM.forms.uc_CRM_BaoGia_ChiTiet
{
    public partial class uc_CRM_BaoGia_ChiTiet_ChiTieuKiemNghiem : UserControl
    {
        public uc_CRM_BaoGia_ChiTiet_ChiTieuKiemNghiem()
        {
            InitializeComponent();
            //radGridView2.DataSource = GetTable();
            //\\VNThanh
            VNThanhLoad();
        }
        static DataTable GetTable()
        {
            //
            // Here we create a DataTable with four columns.
            //
            DataTable table = new DataTable();
            table.Columns.Add("STT", typeof(int));
            table.Columns.Add("MaChiTieu", typeof(string));
            table.Columns.Add("TenChiTieu", typeof(string));
            table.Columns.Add("LoaiMau", typeof(string));
            table.Columns.Add("PhuongPhap", typeof(string));
            table.Columns.Add("SoLuong", typeof(string));
            table.Columns.Add("DonGia", typeof(string));
            table.Columns.Add("ThanhTien", typeof(string));
            // Here we add five DataRows.
            //

            //table.Rows.Add(1,"CT1", "Hàm lượng Protein thô", "Mẫu thực phẩm", "*Δ Mục 8.3 - Manuals of Food quality control 14/7 - FAO : 1986", "2.000.000","2","4.000.000");
            //table.Rows.Add(2,"CT2", "Hàm lượng Ẩm", "Mẫu thực phẩm", "*Δ AOAC 930.15 : 2005", "3.000.000","3","9.000.000");
            //table.Rows.Add(3,"CT3", "Hàm lượng Tro tổng", "Mẫu thực phẩm", "*Δ AOAC 942.05 : 2005", "4.000.000","1","4.000.000");
            //table.Rows.Add(4,"CT4", "Hàm lượng Phosphor", "Mẫu thực phẩm", "*Δ TCVN 1525 : 2007 AOAC 965.17", "2.000.000","2","4.000.000");
            //table.Rows.Add(5,"CT5", "Hàm lượng Canxi (Ca)", "Mẫu thực phẩm", "*AOAC 968.08", "3.000.000","2","6.000.000");
            //table.Rows.Add(6,"CT6", "Hàm lượng Magie (Mg)", "Mẫu thực phẩm", "*AOAC 968.08", "2.000.000","6","12.000.000");
            //table.Rows.Add(7,"CT7", "Hàm lượng Đạm Tiêu Hóa", "Mẫu thực phẩm", "TK - KN - LT - TP", "3.000.000","1","3.000.000");
            //table.Rows.Add(8,"CT8", "Hoạt độ Ure", "Mẫu thực phẩm", "EEC method", "2.000.000","2","4.000.000");
            return table;
        }

        //\\VNThanh
        void VNThanhLoad()
        {
            // Gan su kien.
            this.radGridView2.CellEditorInitialized += new GridViewCellEventHandler(radGridView2_CellEditorInitialized);
            this.radGridView2.CellValueChanged += new GridViewCellEventHandler(radGridView2_CellValueChanged);
            this.radGridView2.UserAddedRow += new GridViewRowEventHandler(radGridView2_UserAddedRow);
            this.radGridView2.UserAddingRow += new GridViewRowCancelEventHandler(radGridView2_UserAddingRow);
            this.radGridView2.CellFormatting += new CellFormattingEventHandler(radGridView2_CellFormatting);
            this.radGridView2.CellValidating += new CellValidatingEventHandler(radGridView2_CellValidating);
            this.radGridView2.UserDeletingRow += new GridViewRowCancelEventHandler(radGridView2_UserDeletingRow);
            this.radGridView2.UserDeletedRow += new GridViewRowEventHandler(radGridView2_UserDeletedRow);

            this.radMenuItem1.Click += new EventHandler(radMenuItem1_Click);

            LoadDataGrid();
        }

        public event ValueChangingEventHandler EvtUserAddedRow;
        private LIM.controller.Thanh_CRMBaoGiaChiTietController _Controller;
        public LIM.controller.Thanh_CRMBaoGiaChiTietController Controller
        {
            get { if (_Controller == null) _Controller = new Thanh_CRMBaoGiaChiTietController(); return _Controller; }
            set { _Controller = value; }
        }
        System.Windows.Forms.BindingSource _CbbKHBindingSource = new BindingSource();
        System.Windows.Forms.BindingSource _GridCTBindingSource = new BindingSource();
        public List<Thanh_ChiTieuKiemNghiem> LstThanh_ChiTieuKiemNghiem = new List<Thanh_ChiTieuKiemNghiem>();
        List<object> LstChiTieuChoosed = new List<object>();
        object _OldThanhTien = null;

        // Load DataGrid
        void LoadDataGrid()
        {
            // Tao 2 combobox cho MaChiTieu va TenChiTieu.
            if (this.radGridView2.Columns["MaChiTieu"] is GridViewMultiComboBoxColumn)
            {
                // Lay danh sach chi tieu.
                List<Thanh_ChiTieuComboBox> lstChiTieu = Controller.GetsChiTieuComboBox().ToList();
                GridViewMultiComboBoxColumn colMaChiTieu = this.radGridView2.Columns["MaChiTieu"] as GridViewMultiComboBoxColumn;
                GridViewMultiComboBoxColumn colTenChiTieu = this.radGridView2.Columns["TenChiTieu"] as GridViewMultiComboBoxColumn;
                colMaChiTieu.DataSource = null;
                colTenChiTieu.DataSource = null;
                if (lstChiTieu.Count > 0)
                {
                    colMaChiTieu.DisplayMember = "MaChiTieu";
                    colMaChiTieu.ValueMember = "RowID";
                    colMaChiTieu.DataSource = lstChiTieu;

                    colTenChiTieu.DisplayMember = "TenChiTieu";
                    colTenChiTieu.ValueMember = "RowID";
                    colTenChiTieu.DataSource = lstChiTieu;
                }
            }
            // Binding source.
            _GridCTBindingSource.DataSource = LstThanh_ChiTieuKiemNghiem;
            this.radGridView2.DataSource = _GridCTBindingSource;
            this.radGridView2.CurrentRow = null;
        }

        // Kiem tra gia tri nhap.
        bool IsDataNotValid()
        {
            GridViewRowInfo row = this.radGridView2.CurrentRow;
            return row.Cells["MaChiTieu"].Value == null || string.IsNullOrWhiteSpace(row.Cells["MaChiTieu"].Value.ToString())
                && row.Cells["TenChiTieu"].Value == null || string.IsNullOrWhiteSpace(row.Cells["TenChiTieu"].Value.ToString())
                && row.Cells["SoLuong"].Value == null || string.IsNullOrWhiteSpace(row.Cells["TenChiTieu"].Value.ToString())
                && row.Cells["DonGia"].Value == null || string.IsNullOrWhiteSpace(row.Cells["DonGia"].Value.ToString());
        }

        // Khi chon 1 chi tieu tu comboboxSet thi set gia tri cho cac column LoaiMau,PhuongPhap,SoLuong,DonGia,ThanhTien.
        void SetColumnValues(int pRowIDChiTieu)
        {
            Thanh_ChiTieuKiemNghiem oThanh_ChiTieuGridView = Controller.GetsChiTieuGridView(pRowIDChiTieu);
            if (oThanh_ChiTieuGridView != null)
            {
                this.radGridView2.CurrentRow.Cells["LoaiMau"].Value = oThanh_ChiTieuGridView.LoaiMau;
                this.radGridView2.CurrentRow.Cells["PhuongPhap"].Value = oThanh_ChiTieuGridView.PhuongPhap;
                int iSoLuong = 1;
                if (this.radGridView2.CurrentRow.Cells["SoLuong"].Value == null || !int.TryParse(this.radGridView2.CurrentRow.Cells["SoLuong"].Value.ToString(), out iSoLuong))
                    this.radGridView2.CurrentRow.Cells["SoLuong"].Value = iSoLuong = 1;
                this.radGridView2.CurrentRow.Cells["DonGia"].Value = oThanh_ChiTieuGridView.DonGia;
                _OldThanhTien = this.radGridView2.CurrentRow.Cells["ThanhTien"].Value;
                if (_OldThanhTien == null)
                    _OldThanhTien = 0;
                this.radGridView2.CurrentRow.Cells["ThanhTien"].Value = oThanh_ChiTieuGridView.DonGia * iSoLuong;
            }
        }

        public void RefreshControl()
        {
            SetControlValues(LstThanh_ChiTieuKiemNghiem);
        }
        // Refresh.
        void radMenuItem1_Click(object sender, EventArgs e)
        {
            RefreshControl();
        }

        // Validate du lieu truoc khi chap nhan record.
        void radGridView2_UserAddingRow(object sender, GridViewRowCancelEventArgs e)
        {
            if (IsDataNotValid())
            {
                e.Cancel = true;
                MessageBox.Show("Dữ liệu nhập vào chưa hợp lệ.\r\nVui lòng kiểm tra lại.", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                foreach (var item in e.Rows)
                {
                    item.ErrorText = string.Empty;
                }
            }
        }

        // Set STT sau khi chap nhan record.
        void radGridView2_UserAddedRow(object sender, GridViewRowEventArgs e)
        {
            e.Row.Cells["STT"].Value = this.radGridView2.Rows.Count;
            if (!LstChiTieuChoosed.Contains(e.Row.Cells["MaChiTieu"].Value))
                LstChiTieuChoosed.Add(e.Row.Cells["MaChiTieu"].Value);
        }

        // Xu ly khi gia tri trong cell thay doi.
        void radGridView2_CellValueChanged(object sender, GridViewCellEventArgs e)
        {
            switch (e.Column.Name)
            {
                case "MaChiTieu":
                    {
                        object RowIDChiTieu = this.radGridView2.CurrentRow.Cells["MaChiTieu"].Value;
                        RadMultiColumnComboBoxElement editor = (RadMultiColumnComboBoxElement)this.radGridView2.ActiveEditor;
                        if (editor != null)
                            RowIDChiTieu = editor.Value;

                        this.radGridView2.CurrentRow.Cells["TenChiTieu"].Value = RowIDChiTieu;
                        SetColumnValues(int.Parse(RowIDChiTieu.ToString()));
                        break;
                    }
                case "TenChiTieu":
                    {
                        object RowIDChiTieu = this.radGridView2.CurrentRow.Cells["TenChiTieu"].Value;
                        RadMultiColumnComboBoxElement editor = (RadMultiColumnComboBoxElement)this.radGridView2.ActiveEditor;
                        if (editor != null)
                            RowIDChiTieu = editor.Value;

                        this.radGridView2.CurrentRow.Cells["MaChiTieu"].Value = RowIDChiTieu;
                        SetColumnValues(int.Parse(RowIDChiTieu.ToString()));
                        break;
                    }
                case "SoLuong":
                case "DonGia":
                    {
                        string sError = string.Empty;
                        int iSoLuong = 1;
                        if (this.radGridView2.CurrentRow.Cells["SoLuong"].Value == null || !int.TryParse(this.radGridView2.CurrentRow.Cells["SoLuong"].Value.ToString(), out iSoLuong) || iSoLuong < 1)
                        {
                            if (e.Column.Name == "SoLuong")
                                sError = "Giá trị nhập vào không hợp lệ.\r\nHệ thống gán giá trị mặc đinh là 1.";
                            this.radGridView2.CurrentRow.Cells["SoLuong"].Value = iSoLuong = 1;
                        }
                        decimal dDonGia = 1;
                        if (this.radGridView2.CurrentRow.Cells["DonGia"].Value == null || !decimal.TryParse(this.radGridView2.CurrentRow.Cells["DonGia"].Value.ToString(), out dDonGia) || dDonGia < 1)
                        {
                            if (e.Column.Name == "DonGia")
                                sError = "Giá trị nhập vào không hợp lệ.\r\nHệ thống gán giá trị mặc đinh là 1.";
                            this.radGridView2.CurrentRow.Cells["DonGia"].Value = dDonGia = 1;
                        }
                        if (!string.IsNullOrEmpty(sError))
                            MessageBox.Show(sError, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);

                        _OldThanhTien = this.radGridView2.CurrentRow.Cells["ThanhTien"].Value;
                        if (_OldThanhTien == null)
                            _OldThanhTien = 0;
                        this.radGridView2.CurrentRow.Cells["ThanhTien"].Value = dDonGia * iSoLuong;

                        break;
                    }
                case "ThanhTien":
                    {
                        if (EvtUserAddedRow != null)
                            EvtUserAddedRow(this, new ValueChangingEventArgs(this.radGridView2.CurrentRow.Cells["ThanhTien"].Value, _OldThanhTien));

                        break;
                    }
            }
        }

        // An column "RowID".
        void radGridView2_CellEditorInitialized(object sender, GridViewCellEventArgs e)
        {
            if (this.radGridView2.CurrentColumn is GridViewMultiComboBoxColumn)
            {
                RadMultiColumnComboBoxElement editor = (RadMultiColumnComboBoxElement)this.radGridView2.ActiveEditor;
                editor.EditorControl.Columns["RowID"].IsVisible = false;
                editor.AutoSizeDropDownToBestFit = true;
                // Set header name
                editor.EditorControl.Columns["MaChiTieu"].HeaderText = "Mã chỉ tiêu";
                editor.EditorControl.Columns["TenChiTieu"].HeaderText = "Tên chỉ tiêu";
                editor.EditorControl.Columns["LoaiMau"].HeaderText = "Loại mẫu";

                //Filter MaChiTieu
                FilterDescriptor oFilterDescriptorMaChiTieu = new FilterDescriptor("MaChiTieu", FilterOperator.Contains, "");
                oFilterDescriptorMaChiTieu.IsFilterEditor = true;
                editor.EditorControl.Columns["MaChiTieu"].FilterDescriptor = oFilterDescriptorMaChiTieu;
                // Filter TenChiTieu
                FilterDescriptor oFilterDescriptorTenChiTieu = new FilterDescriptor("TenChiTieu", FilterOperator.Contains, "");
                oFilterDescriptorTenChiTieu.IsFilterEditor = true;
                editor.EditorControl.Columns["TenChiTieu"].FilterDescriptor = oFilterDescriptorTenChiTieu;
                // Filter LoaiMau
                FilterDescriptor oFilterDescriptorLoaiMau = new FilterDescriptor("LoaiMau", FilterOperator.Contains, "");
                oFilterDescriptorLoaiMau.IsFilterEditor = true;
                editor.EditorControl.Columns["LoaiMau"].FilterDescriptor = oFilterDescriptorLoaiMau;

                editor.EditorControl.FilterDescriptors.LogicalOperator = FilterLogicalOperator.Or;
                editor.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                editor.DropDownStyle = Telerik.WinControls.RadDropDownStyle.DropDown;
                editor.EditorControl.ShowFilteringRow = true;
                editor.AutoFilter = true;
                editor.SelectedIndex = -1;
            }
        }

        // Chuyen format cho "DonGia" va "ThanhTien".
        void radGridView2_CellFormatting(object sender, CellFormattingEventArgs e)
        {
            decimal value = 0;
            switch (e.CellElement.ColumnInfo.Name)
            {
                case "SoLuong":
                    {
                        if (e.CellElement.Value != null && decimal.TryParse(e.CellElement.Value.ToString(), out value))
                        {
                            e.CellElement.Text = string.Format("{0:#,###}", value);
                        }
                        break;
                    }
                case "DonGia":
                    {
                        if (e.CellElement.Value != null && decimal.TryParse(e.CellElement.Value.ToString(), out value))
                        {
                            e.CellElement.Text = string.Format("{0:#,### (đ)}", value);
                        }
                        break;
                    }
                case "ThanhTien":
                    {
                        if (e.CellElement.Value != null && decimal.TryParse(e.CellElement.Value.ToString(), out value))
                        {
                            e.CellElement.Text = string.Format("{0:#,### (đ)}", value);
                        }
                        break;
                    }
            }
        }

        void radGridView2_UserDeletingRow(object sender, GridViewRowCancelEventArgs e)
        {
            int iCount = e.Rows.Count();
            object oValue = null;
            for (int i = 0; i < iCount; i++)
            {
                oValue = e.Rows[i].Cells["MaChiTieu"].Value;
                if (LstChiTieuChoosed.Contains(oValue))
                    LstChiTieuChoosed.Remove(oValue);
            }
        }

        // Delete multi row and reset STT.
        void radGridView2_UserDeletedRow(object sender, GridViewRowEventArgs e)
        {
            SetControlValues(LstThanh_ChiTieuKiemNghiem);
        }

        void radGridView2_CellValidating(object sender, CellValidatingEventArgs e)
        {
            if (e.ActiveEditor != null && LstChiTieuChoosed.Contains(e.Value))
            {
                e.Cancel = true;
                e.Row.ErrorText = "Chỉ tiêu đã được chọn rồi.";
            }
        }

        // Dua du lieu tu doi tuong Thanh_ChiTieuKiemNghiem vao Grid.
        public void SetControlValues(List<Thanh_ChiTieuKiemNghiem> pLstThanh_ChiTieuKiemNghiem)
        {
            LstChiTieuChoosed.Clear();
            LstThanh_ChiTieuKiemNghiem = pLstThanh_ChiTieuKiemNghiem;
            _GridCTBindingSource.DataSource = LstThanh_ChiTieuKiemNghiem;
            this.radGridView2.DataSource = null;
            this.radGridView2.DataSource = _GridCTBindingSource;
            for (int i = 0; i < this.radGridView2.Rows.Count; i++)
            {
                this.radGridView2.CurrentRow = this.radGridView2.Rows[i];
                this.radGridView2.CurrentRow.Cells["STT"].Value = i + 1;
                this.radGridView2.CurrentRow.Cells["MaChiTieu"].Value = LstThanh_ChiTieuKiemNghiem[i].RowIDChiTieu;
                this.radGridView2.CurrentRow.Cells["TenChiTieu"].Value = LstThanh_ChiTieuKiemNghiem[i].RowIDChiTieu;
                this.radGridView2.CurrentRow.Cells["LoaiMau"].Value = LstThanh_ChiTieuKiemNghiem[i].LoaiMau;
                this.radGridView2.CurrentRow.Cells["PhuongPhap"].Value = LstThanh_ChiTieuKiemNghiem[i].PhuongPhap;
                this.radGridView2.CurrentRow.Cells["SoLuong"].Value = LstThanh_ChiTieuKiemNghiem[i].SoLuong;
                this.radGridView2.CurrentRow.Cells["DonGia"].Value = LstThanh_ChiTieuKiemNghiem[i].DonGia;
                _OldThanhTien = this.radGridView2.CurrentRow.Cells["ThanhTien"].Value;
                LstThanh_ChiTieuKiemNghiem[i].ThanhTien = LstThanh_ChiTieuKiemNghiem[i].DonGia * LstThanh_ChiTieuKiemNghiem[i].SoLuong;
                if (_OldThanhTien == null)
                    _OldThanhTien = 0;
                this.radGridView2.CurrentRow.Cells["ThanhTien"].Value = LstThanh_ChiTieuKiemNghiem[i].ThanhTien;
                LstChiTieuChoosed.Add(pLstThanh_ChiTieuKiemNghiem[i].MaChiTieu);
            }
        }
    }
}
